import { useEffect, useRef, useState } from 'react';
import { Html5QrcodeScanner } from 'html5-qrcode';
import styles from './Sao.module.css';
import { NavBar, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import UserProfile from './UserProfile'

// 定义 Html5QrcodeScannerConfig 类型
interface Html5QrcodeScannerConfig {
  qrbox?: { width: number; height: number } | number;
  fps?: number;
  showTorchButtonIfSupported?: boolean;
  showZoomSliderIfSupported?: boolean;
  showScanButton?: boolean;
}

export default function QrScanner() {
  const navigate = useNavigate();
  const [scanResult, setScanResult] = useState<string | null>(null);
  const scannerRef = useRef<Html5QrcodeScanner | null>(null);
  const [showProfile, setShowProfile] = useState<boolean>(false)
  const handleCloseProfile = (): void => {
    setShowProfile(false);
    navigate('/my')
  };
  useEffect(() => {
    const config: Html5QrcodeScannerConfig = {
      qrbox: { width: 250, height: 250 },
      fps: 3,
      showTorchButtonIfSupported: false,
      showZoomSliderIfSupported: false,
      showScanButton: false
    };

    const scanner = new Html5QrcodeScanner('qr-reader', config, false);

    scannerRef.current = scanner;

    const onScanSuccess = (result: string) => {
      scanner.clear();
      console.log(result);
      setScanResult(result);
      Toast.show({
        content: '扫描成功',
        position: 'center',
      });
      // Add navigation after showing the toast
      setTimeout(() => setShowProfile(false), 1000); // Wait 1 second before navigating
    };

    const onScanFailure = (error: string) => {
      console.warn(`QR scan error: ${error}`);
    };

    scanner.render(onScanSuccess, onScanFailure);

    return () => {
      scannerRef.current?.clear();
    };
  }, [navigate]); // Add navigate to dependency array

  const back = () => {
    navigate('/my');
  };

  const handleRescan = () => {
    setScanResult(null);
    scannerRef.current?.render(
      (result: string) => {
        scannerRef.current?.clear();
        setScanResult(result);
        // Also add navigation for rescan success case
        setTimeout(() => setShowProfile(true), 1000);
      },
      (error: string) => {
        console.warn(`Rescan error: ${error}`);
      }
    );
  };

  useEffect(() => {
    handleRescan();
  }, []);

  return (
    <div className={styles.she}>  
      <div style={{ width: '100%', position: 'fixed', top: '0px', color: '#fff' }}>
        <NavBar onBack={back}>二维码扫描</NavBar> 
      </div>   
      <div id="qr-reader" style={{ width: '100%' }}></div>
{/*       
      {scanResult && (
        <div className={styles.resultContainer}>
          <p>扫描结果: {scanResult}</p>
          <button onClick={handleRescan}>重新扫描</button>
        </div>
      )} */}
       {showProfile && (
        <UserProfile userId={scanResult} closeProfile={handleCloseProfile} />
      )}
    </div>
  );
}